package daoOptimize;

import util.JDBCUtils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/*
 * DAO：data(base) access object
 * 封装了针对与数据表的通用的操作(考虑事物)
 * */
public abstract class BaseDAO<T> {

    private Class<T> clazz = null;

//    public BaseDAO() {
//    }

    {
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        Type[] typeArguments = parameterizedType.getActualTypeArguments();//获取了父类的泛型参数
        clazz = (Class<T>) typeArguments[0];//泛型的第一个参数
    }

    //通用的增删改操作------version 2.0 考虑事物
    public int update(Connection connection, String sql, Object... args) { //sql占位符的个数与可变形参的长度一样
        PreparedStatement preparedStatement = null;
        try {
            //1.预编译SQL语句，返回preparedStatement实例
            preparedStatement = connection.prepareStatement(sql);
            //2.填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            //3.执行操作
            return preparedStatement.executeUpdate();//返回影响了几行数据
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            JDBCUtils.closeResourceConnection(null, preparedStatement);
        }
        return 0;
    }


    //通用的查询操作：用于返回数据表中的一条记录(version 2.0，考虑事物)
    public T getInstance(Connection connection, String sql, Object... args) {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //预编译SQL语句
            preparedStatement = connection.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            //执行并获取结果集
            resultSet = preparedStatement.executeQuery();
            //获取结果集中列数
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            //处理数据
            if (resultSet.next()) {
                T t = clazz.newInstance();//创建某个类的对象
                for (int i = 0; i < columnCount; i++) {
                    Object value = resultSet.getObject(i + 1);//获取列的值
                    //获取表的别名getColumnLabel()  获取表的列名getColumnName()
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    //给t对象指定的某个属性，赋值为value。(通过反射)
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);//允许访问私有属性
                    field.set(t, value);
                }
                return t;
            }
        } catch (SQLException | IllegalAccessException | NoSuchFieldException | InstantiationException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResourceConnection(null, preparedStatement, resultSet);
        }
        return null;
    }


    //通用的查询操作：返回表中多条记录的集合(version 2.0 考虑事物)
    public List<T> getForList(Connection connection, String sql, Object... args) {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            //预编译SQL语句
            preparedStatement = connection.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            //执行并获取结果集
            resultSet = preparedStatement.executeQuery();
            //获取结果集中列数
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            //处理数据
            //创建集合对象
            ArrayList<T> list = new ArrayList<>();
            while (resultSet.next()) {
                T t = clazz.newInstance();//创建某个类的对象
                //处理结果集一行数据中每一个列：给t对象指定的属性赋值
                for (int i = 0; i < columnCount; i++) {
                    Object value = resultSet.getObject(i + 1);//获取列的值
                    //获取表的别名getColumnLabel()  获取表的列名getColumnName()
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    //给t对象指定的某个属性，赋值为value。(通过反射)
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);//允许访问私有属性
                    field.set(t, value);
                }
                list.add(t);
            }
            return list;
        } catch (SQLException | IllegalAccessException | NoSuchFieldException | InstantiationException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResourceConnection(null, preparedStatement, resultSet);
        }
        return null;
    }


    //用于查询特殊值的通用方法
    public <E> E getValue(Connection connection, String sql, Object... args) {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //预编译SQL语句，返回preparedStatement实例
            preparedStatement = connection.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            //执行并获取结果集
            resultSet = preparedStatement.executeQuery();
            //处理结果集
            if (resultSet.next()) {
                return (E) resultSet.getObject(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResourceConnection(null, preparedStatement, resultSet);
        }
        return null;
    }
}
